package com.lianyou.chapter06.constraintcomposition;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {CheckCase.CheckCaseValidator.class })
@Documented
public @interface CheckCase {

	String message() default "{org.hibernate.validator.referenceguide.chapter06.constraintcomposition.CheckCase.message}";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };

	CaseMode value();
	static class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {

		private CaseMode caseMode;

		@Override
		public void initialize(CheckCase constraintAnnotation) {
			this.caseMode = constraintAnnotation.value();
		}

		@Override
		public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
			if ( object == null ) {
				return true;
			}

			if ( caseMode == CaseMode.UPPER ) {
				return object.equals( object.toUpperCase() );
			}
			else {
				return object.equals( object.toLowerCase() );
			}
		}
	}
}
